<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Edit, Delete, Select, Close } from '@element-plus/icons-vue'
import { queryModules, delModule, saveModule, selectParentModules } from '@/api/develop'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useAppStore } from '@/store/modules/app'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { getZhHKAndPinyin, getZhCNAndPinyin } from '@/api/common'

defineOptions({
  name: 'ModuleList'
})

const appStore = useAppStore()
const { t } = useI18n()
const formRef = ref()
const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang

const state = reactive({
  searchKey: '',
  // 表格數據
  tableView: [{}],
  queryBody: {
    key: '',
    pageNo: 1,
    pageSize: 1000,
    params: {
      Q_status_I_LT: 4
    },
    sortField: '',
    sortOrder: ''
  },
  // 对话框绑定的数据
  dialogVisible: false,
  dialogTitle: '',
  dialogForm: {
    moduleId: '',
    enName: '',
    hkName: '',
    moduleName: '',
    parentId: '',
    remark: '',
    status: 1,
    sort: 1,
    seq: 1
  },
  dialogRule: {
    moduleName: [
      {
        required: true,
        message: t('module.name') + t('common.notEmpty'),
        trigger: ['blur']
      }
    ]
  },
  nameField: 'moduleName',
  parentList: [{}]
})
onMounted(async () => {
  if (curLang == 'en') {
    state.nameField = 'enName'
  } else if (curLang == 'zh_HK') {
    state.nameField = 'hkName'
  }
  init()
})
useEmitt({
  //刷新列表事件
  name: 'refreshModuleList',
  callback: () => {
    init()
  }
})

// 保存当前记录
const save = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await saveModule(state.dialogForm).then((res) => {
        if (res) {
          ElMessage.success(t(res.message))
          state.dialogVisible = false
          init()
        }
      })
    }
  })
  if (!state.dialogForm.moduleId) {
  }
}
// 刪除当前记录
const deleteOne = (row) => {
  ElMessageBox.confirm(t('module.delMsg'), t('common.warning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await delModule(row.moduleId)
      init()
    })
    .catch(() => {})
}
// 显示对话框
const openDialog = (type, row) => {
  if (type == 'add') {
    state.dialogForm = {
      moduleId: '',
      enName: '',
      hkName: '',
      moduleName: '',
      parentId: '',
      remark: '',
      sort: 1,
      status: 1,
      seq: 1
    }
    getParent(null)
    state.dialogTitle = t('common.add') + ' ' + t('module.module')
  } else {
    //修改
    state.dialogForm.moduleId = row.moduleId
    state.dialogForm.moduleName = row.moduleName
    state.dialogForm.hkName = row.hkName
    state.dialogForm.enName = row.enName
    state.dialogForm.remark = row.remark
    state.dialogForm.parentId = row.parentId
    state.dialogForm.sort = row.sort
    state.dialogForm.status = row.status
    state.dialogForm.seq = row.seq
    getParent(row.moduleId)
    state.dialogTitle = t('common.modify') + ' ' + t('module.module')
  }
  state.dialogVisible = true
}
// 搜索
const handleSearch = () => {
  state.queryBody.key = state.searchKey
  init()
  getParent(null)
}
//渲染页面的接口
const init = async () => {
  appStore.setFooter(false)
  state.tableView = []
  await queryModules(state.queryBody)
    .then((res) => {
      const result = res as any
      var data = result.result.data
      //取一级节点，生成树形结构
      for (const rowAny of data) {
        const row = rowAny as any
        if (row.level == 1) {
          state.tableView.push(row)
          row.displayed = true
          //递归处理各一级节点
          convertData(row, data)
        }
      }
      showOrphans(data)
    })
    .catch(() => {})
}

//显示孤儿节点（即只查询到子节点，父节点没有查询出来的）
const showOrphans = (data: []) => {
  for (const rowAny of data) {
    const row = rowAny as any
    if (!row.displayed) {
      state.tableView.push(row)
      row.displayed = true
    }
  }
}

/**
 * @description 生成某节点的所有子节点，为了显示树形表格
 * @param parent 父节点
 * @author Elwin ZHANG
 * @date 2023-04-07 13:15
 */
const convertData = (parent: any, data: []) => {
  for (const rowAny of data) {
    const row = rowAny as any
    if (row.parentId == parent.moduleId && !row.displayed) {
      if (!parent.children) {
        parent.children = []
      }
      parent.children.push(row)
      row.displayed = true
      //递归处理子节点
      convertData(row, data)
    }
  }
}

//获取父节点
const getParent = async (moduleId) => {
  await selectParentModules(moduleId)
    .then((res) => {
      const result = res as any
      state.parentList = result.data
    })
    .catch(() => {})
}

/**
 * @description 当繁体中文为空时，转换简体中文为繁体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhHKAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //繁体中文为空时才自动转换
  if (state.dialogForm.hkName.length > 0) {
    return
  }
  let data = (await getZhHKAndPinyin(text, 50)) as any
  state.dialogForm.hkName = data.data.zhHK
  //如果英文字段为空，默认为拼音
  if (state.dialogForm.enName.length == 0) {
    state.dialogForm.enName = data.data.pinyin
  }
}

/**
 * @description 当简体中文为空时，转换繁体中文为简体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhCNAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //简体中文为空时才自动转换
  if (state.dialogForm.moduleName.length > 0) {
    return
  }
  let data = (await getZhCNAndPinyin(text, 50)) as any
  state.dialogForm.moduleName = data.data.zhCN
  //如果英文字段为空，默认为拼音
  if (state.dialogForm.enName.length == 0) {
    state.dialogForm.enName = data.data.pinyin
  }
}
</script>
<template>
  <div>
    <!-- 搜索條件卡片 -->
    <el-card class="box-card">
      <el-row :gutter="10" style="padding: 5px 5px; line-height: 28px" align="middle">
        <el-col :sm="5" :md="4" style="text-align: right">{{ $t('common.searchKey') }}</el-col>
        <el-col :sm="19" :md="12" style="text-align: left">
          <el-input
            v-model="state.searchKey"
            @keyup.enter="handleSearch"
            :placeholder="$t('common.inputText') + $t('module.name') + '/' + $t('common.remark')"
          />
        </el-col>
        <el-col :sm="24" :md="8" style="text-align: right">
          <div style="margin-right: -5px">
            <el-button @click="handleSearch" type="primary" size="small" plain
              ><Icon icon="ic:outline-search" /><span>{{ $t('common.query') }}</span></el-button
            >
            <el-button @click="state.searchKey = ''" type="info" size="small" plain>
              <Icon icon="icon-park-solid:clear-format" /><span>{{
                $t('common.reset')
              }}</span></el-button
            >
            <el-button type="success" size="small" plain @click="openDialog('add', {})">
              <Icon icon="material-symbols:add-circle-rounded" /><span>{{ $t('common.add') }}</span>
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="formcard">
      <!-- 搜索結果表格 -->
      <el-table
        :data="state.tableView"
        tooltip-effect="light"
        style="width: 100%; border-color: #a0cfff; font-size: 12px"
        stripe
        row-key="moduleId"
        default-expand-all
        :header-cell-style="{
          background: 'var(--el-color-primary-light-9)',
          color: '#409eff'
        }"
      >
        <el-table-column type="index" min-width="60">
          <template #header>
            <div style="margin-bottom: -10px">
              <Icon icon="ant-design:field-number-outlined" size="24" :title="$t('common.number')"
            /></div>
          </template>
        </el-table-column>
        <el-table-column
          :prop="state.nameField"
          :label="$t('module.name')"
          show-overflow-tooltip
          min-width="120"
        />
        <el-table-column prop="level" :label="$t('menu.level')" min-width="90" align="center" />
        <el-table-column prop="sort" :label="$t('common.sort')" min-width="90" align="center" />
        <el-table-column
          prop="remark"
          :label="$t('common.remark')"
          min-width="200"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column prop="status" :label="$t('common.status')" min-width="80">
          <template #default="{ row }">
            <span v-if="row.status == 1">{{ $t('group.activated') }}</span>
            <span v-else>{{ $t('group.disabled') }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.operation')" width="170">
          <template #default="{ row }">
            <el-button
              type="primary"
              plain
              circle
              size="small"
              :title="$t('common.modify')"
              @click="openDialog('edit', row)"
            >
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
            <el-button
              type="danger"
              plain
              circle
              size="small"
              :title="$t('common.delete')"
              v-if="!row.children"
              @click="deleteOne(row)"
            >
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增或修改模块對話框 -->
    <el-dialog v-model="state.dialogVisible" :title="state.dialogTitle" width="600px" draggable>
      <el-form
        ref="formRef"
        :model="state.dialogForm"
        :rules="state.dialogRule"
        label-width="120px"
      >
        <el-form-item :label="$t('module.name')" prop="moduleName">
          <el-input
            v-model="state.dialogForm.moduleName"
            :placeholder="$t('common.inputText') + $t('module.name')"
            maxlength="50"
            show-word-limit
            @blur="zhHKAndPinyin($event)"
          />
        </el-form-item>
        <el-form-item :label="$t('common.hkName')" prop="hkName">
          <el-input
            v-model="state.dialogForm.hkName"
            :placeholder="$t('common.inputText') + $t('common.hkName')"
            maxlength="50"
            show-word-limit
            @blur="zhCNAndPinyin($event)"
          />
        </el-form-item>
        <el-form-item :label="$t('common.enName')" prop="enName">
          <el-input
            v-model="state.dialogForm.enName"
            :placeholder="$t('common.inputText') + $t('common.enName')"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item :label="$t('common.status')" prop="status">
          <el-switch
            v-model.number="state.dialogForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item :label="$t('common.parentName')" prop="parentId">
          <el-select
            v-model="state.dialogForm.parentId"
            :placeholder="$t('common.selectText')"
            size="default"
          >
            <el-option
              v-for="item in state.parentList"
              :key="item.moduleId"
              :label="item[state.nameField]"
              :value="item.moduleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.sort')" prop="sort">
          <el-input-number
            :min="1"
            :max="999999"
            :step="10"
            v-model="state.dialogForm.sort"
            :placeholder="$t('common.inputText') + $t('common.sort')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('common.remark')" prop="remark">
          <el-input
            v-model="state.dialogForm.remark"
            :placeholder="$t('common.iptRemarks')"
            type="textarea"
            :autosize="{ minRows: 2 }"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="save">
            <el-icon><Select /></el-icon>&nbsp;{{ $t('common.save') }}</el-button
          >
          <el-button @click="state.dialogVisible = false">
            <el-icon> <Close /> </el-icon>&nbsp;{{ $t('common.giveUp') }}</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="less" scoped>
:deep(.el-card__header) {
  border-bottom: 0;
  box-sizing: border-box;
}

:deep(.el-select .el-option .el-input .el-select-dropdown__item) {
  font-size: 12px;
}

:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
  font-size: 12px;
}

:deep(.v-footer) {
  height: 0px;
}
.formcard {
  margin-top: 8px;
}
</style>
